package com.sunwoda.springbootredis.service.impl;

import com.sunwoda.springbootredis.dao.UserDao;
import com.sunwoda.springbootredis.entity.User;
import com.sunwoda.springbootredis.service.OpsStringService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundValueOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @program: springbootredis
 * @description: 操作String
 * @author: SGR
 * @create: 2021-09-13 10:31
 **/
@Service
@Slf4j
public class OpsStringServiceImpl implements OpsStringService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private UserDao userDao;

    /**
    * @Description: 操作String
    * @Param:
    * @return:
    * @Author: SGR
    * @Date: 2021-09-13
    */
    @Override
    public void opsString() {

        redisTemplate.setKeySerializer(new StringRedisSerializer());

        User user = this.userDao.queryById(1L);
        if (ObjectUtils.isEmpty(user)){
            return;
        }
        BoundValueOperations name = redisTemplate.boundValueOps("name");
        name.set(user.getName());

//        获取键值
        log.info("键值："+name.getKey()+"--"+name.get());

//        覆盖旧key，并返回旧key
        Object sex = name.getAndSet("sex");
        log.info("oldValue"+sex);

        List<User> list = this.userDao.queryAll(new User());
        Map<String, String> map = list.stream().collect(Collectors.toMap(User::getName, User::getSex));

        redisTemplate.opsForValue().multiSet(map);


    }
}
